﻿#include "mainwindow.h"

#include <QHostAddress>

#include "ui_mainwindow.h"
using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  setWindowTitle("TCP - 客户端");

  ui->ip->setText("127.0.0.1");
  ui->port->setText("9999");
  ui->disconnect->setEnabled(false);

  m_tcp = new QTcpSocket(this);
  connect(m_tcp, &QTcpSocket::readyRead, [=]() {
    QByteArray recvMsg = m_tcp->readAll();
    ui->record->append("服务器Say: " + recvMsg);
  });
  connect(m_tcp, &QTcpSocket::connected, this, [=]() {
    ui->record->append("连接服务器成功!!!");
    m_status->setPixmap(QPixmap(":/connect.png").scaled(30, 30));
  });
  connect(m_tcp, &QTcpSocket::disconnected, this, [=]() {
    if (ui) {
      ui->record->append("服务器已经断开, ...");
      ui->connectServer->setEnabled(true);
      ui->disconnect->setEnabled(false);
      m_status->setPixmap(QPixmap(":/disconnect.png").scaled(30, 30));
    }
  });

  m_status = new QLabel;
  m_status->setPixmap(QPixmap(":/disconnect.png").scaled(30, 30));
  ui->statusBar->addWidget(new QLabel("连接状态: "));
  ui->statusBar->addWidget(m_status);
}

MainWindow::~MainWindow() {
  delete ui;
  ui = nullptr;
}

void MainWindow::on_connectServer_clicked() {
  QString ip = ui->ip->text();
  unsigned short port = ui->port->text().toInt();
  m_tcp->connectToHost(QHostAddress(ip), port);
  ui->connectServer->setEnabled(false);
  ui->disconnect->setEnabled(true);
}

void MainWindow::on_sendMsg_clicked() {
  QString sendMsg = ui->msg->toPlainText();
  // 加密
  m_tcp->write(sendMsg.toUtf8());
  ui->record->append("客户端Say: " + sendMsg);
  ui->msg->clear();
}

void MainWindow::on_disconnect_clicked() {
  m_tcp->close();
  ui->connectServer->setEnabled(true);
  ui->disconnect->setEnabled(false);
}
